//
//  LoginViewController.m
//  MyNewProject
//
//  Created by sun on 2019/2/13.
//  Copyright © 2019 sun. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "CQCountDownButton.h"
#import "SVProgressHUD.h"
#import "YPLoginDataModels.h"
#import "ForgetPasswordVC.h"

#import "WXLoginModel.h"

@interface LoginViewController()


@property (nonatomic, strong) CQCountDownButton *countDownButton;

@property (nonatomic, strong) UITextField * accountTextField;

@property (nonatomic, strong) UITextField * pWTextField;
@end

@implementation LoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navBarAlpha = 0;
    [self initNav];
    [self initView];
    [self getOtherLoginRequest];
}
-(void)initView {
    /*
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(0,0,105,105);
    imageView.center = CGPointMake(self.view.centerX, 30 + imageView.height/2 + SKTopBar_Height);
    imageView.image = [UIImage imageNamed:@"logo"];
    [self.view addSubview:imageView];
    */
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(30, 74 + SKTopBar_Height, self.view.width - 60, 31);
    titleLabel.text = @"您好，请登录！";
    titleLabel.font = SKFONT_Medium(30);
    titleLabel.textColor = SKColorWithHex(0x262626);
    [self.view addSubview:titleLabel];
    
    UITextField * accountTextField =[[UITextField alloc] initWithFrame:CGRectMake(43, titleLabel.bottom + 70, SCREEN_WIDTH-43*2, 40)];
    accountTextField.font = [UIFont systemFontOfSize:16.0f];
    accountTextField.placeholder = @"请输入你的手机号";
    _accountTextField = accountTextField;
    [self.view addSubview:accountTextField];
    UIView *lineView = [[UIView alloc] init];
    lineView.frame = CGRectMake(42.5,accountTextField.bottom,SCREEN_WIDTH - 42.5 *2,0.5);
    lineView.backgroundColor = [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0];
    [self.view addSubview:lineView];
    
    
    UITextField * pWTextField =[[UITextField alloc] init];
    pWTextField.font = [UIFont systemFontOfSize:16.0f];
    _pWTextField = pWTextField;
    [self.view addSubview:pWTextField];
    switch (_myLoginmethod) {
        case MIMALOGIN:
        {
            pWTextField.frame = CGRectMake(43, lineView.bottom + 36, SCREEN_WIDTH-43*2, 40);
            pWTextField.placeholder = @"请输入密码";
            pWTextField.secureTextEntry = true;

        }
            break;
        case YANZHENGMALOGIN:
        {
            pWTextField.frame = CGRectMake(43, lineView.bottom + 36, SCREEN_WIDTH-43*2-97, 40);
            pWTextField.placeholder = @"请输入验证码";
            pWTextField.secureTextEntry = false;
            [self countCutDown:pWTextField];
        }
            break;
            
        default:
            break;
    }
    
   
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.frame = CGRectMake(42.5,pWTextField.bottom,SCREEN_WIDTH - 42.5 *2,0.5);
    lineView1.backgroundColor = [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0];
    [self.view addSubview:lineView1];
    
    UIFont * font = SKFONT_BOLD_SIZE(18);
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(43, lineView1.bottom +49 , SCREEN_WIDTH -43 *2 , 44);
    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    button.backgroundColor = SKColorWithHex(0xE33030);
    [button setTitle:@"登  录" forState:UIControlStateNormal];
    button.titleLabel.font = font;
    [button setTitleColor:SKColorWithHex(0xFFFFFF) forState:UIControlStateNormal];
    [button addTarget:self action:@selector(loginDeal:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    
    UIButton *forgetPassword = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetPassword.frame = CGRectMake(43,  button.bottom + 20, SCREEN_WIDTH -43 *2 , 20);
    forgetPassword.titleLabel.font = SKFONT_SIZE(15);
    forgetPassword.backgroundColor = SKColorWithHex(0xFFFFFF);
    [forgetPassword setTitleColor:SKColorWithHex(0x444444) forState:UIControlStateNormal];
    [forgetPassword setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetPassword addTarget:self action:@selector(forgetPasswordButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetPassword];
    
    UIButton *switchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    switchBtn.frame = CGRectMake(43,  button.bottom + 60, SCREEN_WIDTH -43 *2 , 20);
    switchBtn.titleLabel.font = SKFONT_SIZE(15);
    switchBtn.backgroundColor = SKColorWithHex(0xFFFFFF);
    [switchBtn setTitleColor:SKColorWithHex(0x444444) forState:UIControlStateNormal];
    switch (_myLoginmethod) {
        case MIMALOGIN: {
            [switchBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
            switchBtn.tag = 1000000000;
        }
            break;
        case YANZHENGMALOGIN: {
            [switchBtn setTitle:@"密码登录" forState:UIControlStateNormal];
            switchBtn.tag = 1000000001;
        }
            break;
        default:
            break;
    }
    [switchBtn addTarget:self action:@selector(kindLoginDeal:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:switchBtn];
}

/// 其他登录
- (void)otherLogin {
    UIButton *qqLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [qqLoginBtn setImage:SKIMAGE_NAMED(@"login_qq") forState:UIControlStateNormal];
    [qqLoginBtn addTarget:self action:@selector(qqButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:qqLoginBtn];

    UIButton *wxLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [wxLoginBtn setImage:SKIMAGE_NAMED(@"login_wx") forState:UIControlStateNormal];
    [wxLoginBtn addTarget:self action:@selector(wxButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wxLoginBtn];

    UIView *bottomLine = [[UIView alloc] init];
    bottomLine.backgroundColor = [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0];
    [self.view addSubview:bottomLine];

    UILabel *label = [[UILabel alloc] init];
    label.textColor = SKColorWithHex(0x999999);
    label.font = SKFONT_SIZE(13);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"其他账号登录";
    label.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label];

    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(30);
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];

    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(bottomLine);
        make.width.mas_equalTo(95);
    }];

    //    [qqLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.bottom.mas_offset(-(SKBottomSafe_Height + 24.5));
    //        make.centerX.mas_equalTo(label.mas_centerX).mas_offset(-39);
    //        make.top.mas_equalTo(bottomLine.mas_bottom).mas_offset(32.5);
    //    }];

    [wxLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-(SKBottomSafe_Height + 24.5));
        make.centerX.mas_offset(0);
        make.top.mas_equalTo(bottomLine.mas_bottom).mas_offset(32.5);
    //        make.centerY.mas_equalTo(qqLoginBtn);
    //        make.centerX.mas_equalTo(label.mas_centerX).mas_offset(39);
    }];
}
#pragma mark -- mark EVENT

/**
 qq登录

 @param sender sender
 */
- (void)qqButtonClick:(UIButton *)sender {
    
}

/**
 微信登陆按钮

 @param sender sender
 */
- (void)wxButtonClick:(UIButton *)sender {
    SKWeakSelf;
    [AppDelegate wj_wxLoginComplete:^(NSDictionary *userInfo) {
        [weakSelf wxLoginWithUserInfo:userInfo];
    }];
}

/// 忘记密码
/// 
/// @param sender sender
- (void)forgetPasswordButtonClick:(UIButton *)sender {
    ForgetPasswordVC *vc = [[ForgetPasswordVC alloc] init];
    [self.navigationController pushViewController:vc animated:true];
}

#pragma mark -- mark 微信登录
- (void)wxLoginWithUserInfo:(NSDictionary *)userInfo {
    NSString *unionid = userInfo[@"unionid"];
    NSString *openid = userInfo[@"openid"];
    NSString *subscribe = userInfo[@"subscribe"] ? userInfo[@"subscribe"] : @"0";
    NSString *nickname = userInfo[@"nickname"];
    NSString *subscribe_time = userInfo[@"subscribe_time"];
    NSString *avastar = userInfo[@"headimgurl"];
    NSString *device = @"1";
    NSString *sign = @"yupinyouxuan*****yupinyouxuan";
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:@{@"device":device, @"sign":sign}];
    if (unionid) {
        [param addEntriesFromDictionary:@{@"unionid":[NSString stringWithFormat:@"%@", unionid]}]; }
    if (openid) {
        [param addEntriesFromDictionary:@{@"openid":[NSString stringWithFormat:@"%@", openid]}]; }
    if (subscribe) {
        [param addEntriesFromDictionary:@{@"subscribe":[NSString stringWithFormat:@"%@",subscribe]}]; }
    if (nickname) {
        [param addEntriesFromDictionary:@{@"nickname":[NSString stringWithFormat:@"%@", nickname]}]; }
    if (subscribe_time) {
        [param addEntriesFromDictionary:@{@"subscribe_time":[NSString stringWithFormat:@"%@", subscribe_time]}]; }
    if (avastar) {
        [param addEntriesFromDictionary:@{@"avastar":[NSString stringWithFormat:@"%@", avastar]}]; }
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Login/weixinLogin" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WXLoginModel *model = [WXLoginModel modelWithDictionary:response];
        if ([model isSuccess]) {
            // 登陆成功
            if (model.data.mobile.length > 0) {
                // 有手机号
                // 登陆成功
                SKUserUserDefaults_Save(response[@"data"], @"UserInfo");
                YPLoginBaseClass * baseLogin = [YPLoginBaseClass modelObjectWithDictionary:response];
                [UserInfoSingleton shareInstance].userInfo = baseLogin.userInfo;
                if (self.myLoginResult) {
                    self.myLoginResult([UserInfoSingleton shareInstance].userInfo);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                // 没有手机号
                // 绑定手机号
                RegisterViewController *vc = [[RegisterViewController alloc] init];
                vc.wxInfo = model.data;
                [weakSelf.navigationController pushViewController:vc animated:true];
            }
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
    
}



#pragma mark -- 倒计时
-(void)countCutDown:(UITextField*)pWTextField
{
    SKWeakSelf;
    self.countDownButton = [[CQCountDownButton alloc] initWithDuration:10 buttonClicked:^{
        NSLog(@"按钮点击");
        //------- 按钮点击 -------//
        [SVProgressHUD showWithStatus:@"正在获取验证码..."];
        [YQNetworking postWithUrl:@"Login/sendsms" refreshRequest:YES cache:NO params:@{@"mobile":weakSelf.accountTextField.text,@"sign":@"yupinyouxuan*****yupinyouxuan"} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        } successBlock:^(id response) {
            NSDictionary *dic = (NSDictionary*)response;
            if ([dic[@"status"] isEqualToString:@"ok"])
            {
                [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
                [weakSelf.countDownButton startCountDown];
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:@"获取失败，请重试"];
                weakSelf.countDownButton.enabled = YES;
            }
        } failBlock:^(NSError *error) {
            
        }];
        // 请求数据
    } countDownStart:^{
        //------- 倒计时开始 -------//
        NSLog(@"倒计时开始");
    } countDownUnderway:^(NSInteger restCountDownNum) {
        //------- 倒计时进行中 -------//
        [weakSelf.countDownButton setTitle:[NSString stringWithFormat:@"重新获取(%ld)", restCountDownNum] forState:UIControlStateNormal];
    } countDownCompletion:^{
        //------- 倒计时结束 -------//
        [weakSelf.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        NSLog(@"倒计时结束");
    }];
    
    [self.view addSubview:self.countDownButton];
    //------- 按钮的属性设置 -------//
    self.countDownButton.frame = CGRectMake(pWTextField.right+10, pWTextField.top,SCREEN_WIDTH -pWTextField.width -10 - 43*2, 40);
    [self.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.countDownButton setTitleColor:SKColorWithHex(0x4444444) forState:UIControlStateNormal];
    [self.countDownButton setTitleColor:SKColorWithHex(0x999999) forState:UIControlStateDisabled];
    self.countDownButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
    [self.view addSubview:self.countDownButton];
}
#pragma mark --登录设置

-(void)loginDeal:(UIButton*)sender
{
    
    if (IsStrEmpty(_accountTextField.text)) {
        [self.view makeToast:@"电话不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    if (IsStrEmpty(_pWTextField.text)) {
        if (_myLoginmethod == MIMALOGIN) {
            [self.view makeToast:@"密码不能为空" duration:1 position:CSToastPositionCenter];
        }
        else
        {
            [self.view makeToast:@"验证码不能为空" duration:1 position:CSToastPositionCenter];
        }
        return;
    }
    [YQNetworking postWithUrl:@"Login/login" refreshRequest:YES cache:NO params:@{@"mobile":_accountTextField.text,@"code":(_myLoginmethod == MIMALOGIN?@"":_pWTextField.text),@"password":(_myLoginmethod == MIMALOGIN?_pWTextField.text:@""),@"type":(_myLoginmethod == MIMALOGIN?@"1":@"2")} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        YPLoginBaseClass * baseLogin = [YPLoginBaseClass modelObjectWithDictionary:response];
        
        if ([baseLogin.status isEqualToString:@"ok"]) {
            NSDictionary * dic = (NSDictionary *)response;
            SKUserUserDefaults_Save(dic[@"user_info"] , @"UserInfo");
            [UserInfoSingleton shareInstance].userInfo = baseLogin.userInfo;
            [self.navigationController popViewControllerAnimated:YES];
            if (self.myLoginResult) {
                self.myLoginResult([UserInfoSingleton shareInstance].userInfo);
            }
        }
        else
        {
            [self.view makeToast:SafeString(baseLogin.msg) duration:1 position:CSToastPositionCenter];
        }
    } failBlock:^(NSError *error) {
        
    }];
    
   
}
- (void)getOtherLoginRequest {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Login/getShow" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        if ([response[@"status"] isEqualToString:@"ok"] && [response[@"data"][@"is_show"] intValue]) {
            [weakSelf otherLogin];
        }
    } failBlock:^(NSError *error) {
        
    }];
}
-(void)kindLoginDeal:(UIButton*)sender
{
    for (id view  in [self.view subviews]) {
        
        if (view != self.gk_navigationBar) {
            [view removeFromSuperview];
        }
    }
    if (sender.tag == 1000000000) {
        _myLoginmethod = YANZHENGMALOGIN;
        
    }else
    {
        _myLoginmethod = MIMALOGIN;

    }
    [self initView];
    
}
-(void)initNav
{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton  * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
    [backBtn setTitle:@"  返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:SKColorWithHex(0x333333) forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
    
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backDeal:) forControlEvents:UIControlEventTouchUpInside];
    self.gk_navItemLeftSpace = 10;

    self.gk_navLeftBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:backBtn] ;
    self.gk_navItemLeftSpace = 10;
    
    UIButton  * customBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    [customBtn setTitle:@"注册" forState:UIControlStateNormal];
    [customBtn setTitleColor:SKColorWithHex(0x444444) forState:UIControlStateNormal];
    customBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
    [customBtn addTarget:self action:@selector(registerBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.gk_navRightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customBtn];
    
}
-(void)backDeal:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)registerBtn:(UIButton*)sender
{
    RegisterViewController * registerVC = [RegisterViewController new];
    SKWeakSelf;
    registerVC.myRegisterResult = ^(id model) {
        if (weakSelf.myLoginResult) {
            weakSelf.myLoginResult(model);
        }
    };
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardHeight = keyboardRect.size.height;
    
    CGRect frame = self.view.bounds;
    frame.size.height -= keyboardHeight;
    
    SKLog(@"%f",self.pWTextField.bottom - keyboardRect.origin.y);
    if (self.pWTextField.bottom - keyboardRect.origin.y > 0) {
        
        self.view.top =-(self.pWTextField.bottom - keyboardRect.origin.y);
    }
    
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    self.view.top =0;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
